import re
from rest_framework import serializers
from users.models import User
from rest_framework_jwt.settings import api_settings
from django_redis import get_redis_connection

class UserSerializers(serializers.ModelSerializer):
    # 显示指明模型类中没有的字段 write_only = True 表示这个字段只参与到反序列化过程
    password2 = serializers.CharField(max_length = 20, min_length = 8, write_only = True)
    sms_code = serializers.CharField(max_length = 6, min_length = 6, write_only = True)
    allow = serializers.CharField(write_only = True)
    token = serializers.CharField(read_only = True)

    class Meta:
        model = User
        fields = ('username', 'password', 'password2', 'mobile', 'allow', 'sms_code', 'id', 'token')

        extra_kwargs = {
            "password":{
                "max_length":20,
                "min_length":8,
                "write_only":True
            },
            "username":{
                "max_length":20,
                "min_length":5
            }
        }

        # 验证手机号格式
    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}', value):
            raise serializers.ValidationError('手机格式不正确')

        return value


        # 验证选中状态
    def validate_allow(self, value):
        if value != 'true':
            raise serializers.ValidationError('协议未同意')

        return value


        # 验证两次密码
    def validata(self, attrs):
        # 密码判断
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError('两次密码不一致')

        # 短信验证码判断
        # 1 获取缓存中的短信验证码
        conn = get_redis_connection('sms_code')
        real_sms_code = conn.get('sms_code_%s'%attrs['mobile'])
        # 2 判断验证码是否失效
        if real_sms_code is None:
            raise serializers.ValidationError('验证码已失效，请重新获取')
        # 3 校验用户输入的短信验证码是否正确
        if attrs['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('短信验证码输入有误')

        return attrs

        # 保存
    def create(self, validated_data):
        # del validated_data['password2']
        # del validated_data['allow']
        # del validated_data['sms_code']
        # user = User.objects.create_user(validated_data)
        # create_user创建用户对象的时候会对密码进行加密处理 create也能 创建用户对象，但不会进行密码加密
        user = User.objects.create_user(username = validated_data['username'], password = validated_data['password'],
    mobile = validated_data['mobile'])

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        # 给user对象添加token属性
        user.token = token

        return user